package ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.hardware.bcreader.BCRBarCodeValue;
import android.hardware.bcreader.BCRListener;
import android.hardware.bcreader.BCRManager;
import android.hardware.bcreader.BCRTicketInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.ExpandableListView;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sxpjyy.monkey.mobilenurse.R;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapters.OrdersCheckAdapter;
import mytools.ApplicationUtil;
import mytools.DateUtil;
import mytools.MyBaseActivity;
import objects.InPatient;
import objects.OrderDetail;
import service.WebService;

public class OrdersCheckActivity_2 extends MyBaseActivity implements SwipeRefreshLayout.OnRefreshListener, Switch.OnCheckedChangeListener, RadioGroup.OnCheckedChangeListener {

    private String TAG = "BCRSample";
    private BCRManager mBCRManager;
    private BCRTicketInfo mBCRTicketInfo[] = {null, null};

    private String mServiceResult = null;
    private String mScanResult;
    private List<OrderDetail> mYZJHList;
    private List<OrderDetail> parentList;

    private ProgressDialog progressDialog;
    private MyHandler handler;

    private Toolbar mToolbar;
    private Switch mSwitch;
    private TextView mBRXMText;
    private RadioGroup mRadioGroup;

    private SwipeRefreshLayout mSwipeRefreshLayout;
    private ExpandableListView mExpandableListView;
    private OrdersCheckAdapter mOrdersCheckAdapter;

    private String ZYH;
    private String mStartDate;
    private String mEndDate;

    private String HDBZ = "0";
    private String LXXH = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orders_check_2);
        onBindUI();

        handler = new MyHandler(this);
        BCRListener mListener = new MyListener();
        mBCRManager = BCRManager.getInstance();
        mBCRManager.registerListener(mListener);

        mSwipeRefreshLayout.setColorSchemeResources(R.color.holo_green_dark, R.color.holo_green_light, R.color.holo_orange_light, R.color.holo_red_light);
        mSwipeRefreshLayout.setOnRefreshListener(this);

        mSwitch.setOnCheckedChangeListener(this);

        mOrdersCheckAdapter = new OrdersCheckAdapter(this);
        mExpandableListView.setAdapter(mOrdersCheckAdapter);

        mRadioGroup.setOnCheckedChangeListener(this);
    }

    private void onBindUI() {
        mToolbar = findViewById(R.id.oc_toolbar);
        mBRXMText = findViewById(R.id.oc_tb_brxm);
        mSwitch = findViewById(R.id.oc_tb_switch);
        mSwipeRefreshLayout = findViewById(R.id.oc_swipe);
        mExpandableListView = findViewById(R.id.oc_expand);
        mRadioGroup = findViewById(R.id.filter_radiogroup);
    }

    @Override
    protected void onResume() {
        super.onResume();
        InPatient inPatient = getMyApplication().getInPatient();
        if (inPatient != null) {
            ZYH = inPatient.getZYH();
            if (ZYH != null) {
                setToolbar(inPatient.getBRXM());
                Date date = new Date();
//                String dateString = myApplication.getSdf().format(date);

                String dateString  = DateUtil.getDFFormatString(date);
                mStartDate = dateString;
                mEndDate = dateString;
                doFlushData(true);
            }
        }
    }

    @Override
    public void onRefresh() {
        doFlushData(false);
    }

    private void setToolbar(String brxm) {
        mToolbar.setTitle("计划复核");   //设置标题
        mToolbar.setTitleTextColor(Color.WHITE);
        mBRXMText.setText(brxm);
        mBRXMText.setTextColor(Color.WHITE);
        setSupportActionBar(mToolbar);   //必须使用
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            mSwitch.setText(" 已复核 ");
        } else {
            mSwitch.setText(" 未复核 ");
        }
        doFilter();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        doFilter();
    }

    //扫码监听
    private class MyListener implements BCRListener {
        @Override
        public void onScanFinished(int scanType, String elapseTime) {
            Log.d(TAG, "onScanFinished");
            mBCRTicketInfo = mBCRManager.getTicketInfo();
            Message msg = new Message();
            if (mBCRTicketInfo != null) {
                msg.what = 0x11;
            } else {
                msg.what = 0x99;
            }
            handler.sendMessage(msg);
        }

        @Override
        public void onOpened(boolean isReady) {
            Log.d(TAG, "onOpened");
            if (isReady) {
                mBCRManager.enableCode(BCRBarCodeValue.CODE_TYPE_DATA_MATRIX);
                mBCRManager.enableCode(BCRBarCodeValue.CODE_TYPE_INTERLEAVED_2_OF_5);
                mBCRManager.enableCode(BCRBarCodeValue.CODE_TYPE_PDF417);
                mBCRManager.startScan(BCRManager.SCAN_TYPE_SINGLE, BCRManager.SCAN_MODE_CONTINUE);
            }
        }
    }

    private static class MyHandler extends Handler {

        WeakReference<OrdersCheckActivity_2> mActivity;

        MyHandler(OrdersCheckActivity_2 activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            OrdersCheckActivity_2 activity = mActivity.get();
            activity.cancelProgressBar();
            switch (msg.what) {
                case 0x99:
                    Toast.makeText(activity, "获取扫描结果失败！", Toast.LENGTH_SHORT).show();
                    activity.mBCRManager.stopScan();
                    break;
                case 0x11: //获取扫描结果成功
                    activity.mBCRManager.stopScan();
                    String result = activity.mBCRTicketInfo[0].getTicketValue();
                    if (result != null && !result.equals("") && !result.equals("failed")) {
                        activity.mScanResult = result;
                    }
                    boolean isFound = false;
                    String tmbhs = "";
                    for (OrderDetail parent : activity.parentList) {
                        if (parent.getTMBH().equals(activity.mScanResult)) {
                            isFound = true;
                            tmbhs = parent.getTMBH();
                            break;
                        }
                    }
                    if (isFound) {
                        String[] parms = {activity.getMyApplication().getUser().getYGDM(), tmbhs};
                        activity.new MyCheckOrdersTask().execute(parms);
                    } else {
                        Toast.makeText(activity, "当前界面不存在该条码！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    //显示等待对话框
    private void showProgressBar(Context context) {
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("正在获取信息。。。");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    //取消显示等待对话框
    private void cancelProgressBar() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.cancel();
            progressDialog = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case 1300:
            case 1301:
                mBCRManager.open(this);
                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_order_check, menu); //解析menu布局文件到menu
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//        Toast.makeText(OrdersCheckActivity_2.this, item.getTitle(), Toast.LENGTH_SHORT).show();
        switch (item.getItemId()) {
            case R.id.item_selectall:
                boolean isSelectAll = !mOrdersCheckAdapter.isSeleceAll();
                mOrdersCheckAdapter.selectAll(isSelectAll);
                break;
            case R.id.item_check:
                doUpdateCheck();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void doFlushData(boolean isShowProgress) {
        if (isShowProgress) {
            showProgressBar(this);
        }
        String[] parms = {ZYH, mStartDate, mEndDate};
        new MyGetYZJHTask().execute(parms);
    }

    /**
     * 获取医嘱计划操作
     */
    private class MyGetYZJHTask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
//            isEcecuting[2] = true;
        }

        @Override
        protected String doInBackground(String... parms) {
            WebService getYZJHWebService = new WebService(OrdersCheckActivity_2.this);
            getYZJHWebService.setMETHOD_NAME("getYZJHResult");
            String result;
            getYZJHWebService.setPARMS(parms);
            result = getYZJHWebService.getServerData();
            if (result == null || result.equals("null") || result.equals("") || result.equals("[]")) {
                return "获取医嘱计划列表为空！";
            } else {
                if (!result.equals(mServiceResult)) {
                    mServiceResult = result;
                    Gson gson = new Gson();
                    mYZJHList = gson.fromJson(mServiceResult, new TypeToken<List<OrderDetail>>() {
                    }.getType());
                    if (mYZJHList != null && mYZJHList.size() > 0) {
                        Collections.sort(mYZJHList, (arg0, arg1) -> arg1.getYZZX().compareTo(arg0.getYZZX()));
                        return null;
                    } else {
                        return "获取医嘱计划列表失败!";
                    }
                } else {
                    return "医嘱计划数据未发生变化!";
                }
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            cancelProgressBar();
            if (mSwipeRefreshLayout.isRefreshing()) {
                mSwipeRefreshLayout.setRefreshing(false);
            }
            if (s != null) {
//                if (!s.equals("医嘱计划数据未发生变化!")) {
                Toast.makeText(OrdersCheckActivity_2.this, s, Toast.LENGTH_SHORT).show();
//                }
            } else {
                doFilter();
            }
        }
    }

    private void doSetData() {

        parentList = new ArrayList<>();
        Map<OrderDetail, List<OrderDetail>> mDataSet = new HashMap<>();
        for (OrderDetail ocYZJH : mYZJHList
                ) {
            boolean condition = false;
            if (ocYZJH.getHDBZ() == null) {
                if (HDBZ.equals("0")) {
                    condition = true;
                }
            } else {
                if (ocYZJH.getHDBZ().equals(HDBZ)) {
                    condition = true;
                }
            }

            if (!LXXH.equals("")) {
                condition = condition && ocYZJH.getLXXH().equals(LXXH);
            }
            if (condition) {
                if (ocYZJH.getYZZX().equals("1")) {
                    parentList.add(ocYZJH);
                    mDataSet.put(ocYZJH, null);
                } else {
                    for (OrderDetail parentYZJH : parentList
                            ) {
                        if (ocYZJH.getTMBH().equals(parentYZJH.getTMBH())) {
                            List<OrderDetail> childList = mDataSet.get(parentYZJH);
                            if (childList == null) {
                                childList = new ArrayList<>();
                            }
                            childList.add(ocYZJH);
                            mDataSet.put(parentYZJH, childList);
                        }
                    }
                }
            }
        }
        mOrdersCheckAdapter.setDataSets(mDataSet);
        mOrdersCheckAdapter.notifyDataSetChanged();
    }

    private void doFilter() {
        HDBZ = mSwitch.isChecked() ? "1" : "0";
        int checkedId = mRadioGroup.getCheckedRadioButtonId();
        switch (checkedId) {
            case R.id.filter_all:
                LXXH = "";
                break;
            case R.id.filter_sy:
                LXXH = "1";
                break;
            case R.id.filter_zs:
                LXXH = "2";
                break;
            case R.id.filter_kf:
                LXXH = "3";
                break;
            case R.id.filter_other:
                LXXH = "4";
                break;
        }
        doSetData();
    }

    private void doUpdateCheck() {
        if (parentList != null && parentList.size() > 0) {
            StringBuilder tmbhs = new StringBuilder();
            for (int i = 0; i < parentList.size(); i++) {
                if (mOrdersCheckAdapter.isParentChoiced(i)) {
                    OrderDetail orderDetail = mOrdersCheckAdapter.getParent(i);
                    if (tmbhs.toString().equals("")) {
                        tmbhs.append(orderDetail.getTMBH());
                    } else {
                        tmbhs.append(",").append(orderDetail.getTMBH());
                    }
                }
            }
            String[] parms = {getMyApplication().getUser().getYGDM(), tmbhs.toString()};
            showProgressBar(this);
            new MyCheckOrdersTask().execute(parms);
        }
    }

    /**
     * 核对、执行医嘱操作
     */
    private class MyCheckOrdersTask extends AsyncTask<String, Integer, String> {

        private boolean taskSucceed = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            WebService checkWebService = new WebService(OrdersCheckActivity_2.this);
            checkWebService.setMETHOD_NAME("checkYZJH");
            String result;
            checkWebService.setPARMS(params);
            result = checkWebService.getServerData();
            if (result == null || result.equals("null") || result.equals("0")) {
                taskSucceed = false;
                return "计划复核失败！";
            } else {
                taskSucceed = true;
                return "计划复核成功！\n" + result;
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            cancelProgressBar();
            if (taskSucceed) {
                doFlushData(true);
            }
            Toast.makeText(OrdersCheckActivity_2.this, s, Toast.LENGTH_SHORT).show();
        }
    }
}
